package com.demo.init;

import com.demo.config.AppConfig;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.startup.Tomcat;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletException;
import java.io.File;

/**
 * @author kh
 * Created by on  2022-02-14 15:08
 */
public class MySpringApplication {

	public static void run() throws ServletException, LifecycleException {

		AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();

		context.register(AppConfig.class);

		context.refresh();

		File base = new File(System.getProperty("java.io.tmpdir"));

		Tomcat tomcat = new Tomcat();

		tomcat.setPort(9000);

		Context rootContext = tomcat.addContext("/", base.getAbsolutePath());

		DispatcherServlet dispatcherServlet = new DispatcherServlet(context);

		Tomcat.addServlet(rootContext, "my", dispatcherServlet).setLoadOnStartup(1);

		rootContext.addServletMapping("/","my");

		tomcat.start();

		tomcat.getServer().await();

		/*File base = new File(System.getProperty("java.io.tmpdir"));
		Tomcat tomcat = new Tomcat();

		tomcat.setPort(9000);
		*//**
		 * addWebapp：表示的是一个web项目
		 *contextPath tomcat的访问路径
		 * tomcat.addWebapp("/", "/Users/mac/Documents/index.html");
		 *//*
//		tomcat.addWebapp("/", base.getAbsolutePath());
		Context rootConetxt = tomcat.addContext("/", base.getAbsolutePath());
		tomcat.start();
		tomcat.getServer().await();*/
	}
}
